# 合并购物车工具方法
import pickle, base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    cart_str = request.COOKIES.get('carts')
    if cart_str:
        cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
    else:
        return response

    # 三个变量，new_cart_dict用来存sku_id:count
    # new_add_selected cookie中 被勾选的sku_id 如果redis里有相同的商品 就覆盖 以cookie里的数据主
    # new_remove_selected cookie中 没有被勾选的sku_id  如果redis里有相同的商品 就删掉 以cookie里的数据主
    new_cart_dict = {}  # 保存商品和数量
    new_add_selected = []  # 保存被勾选的商品编号
    new_remove_selected = []  # 保存被勾选的商品编号

    """
    cookis 里存的格式
        {
          "sku_id1":{
            "count":1,
            "selected":True
          },
          "sku_id2":{
            "count":2,
            "selected":False
          }
        }
    """
    # 遍历cookie中购物车字典，将要合并的数据添加到数据容器(重要)
    for sku_id, cart_dict in cart_dict.items():
        new_cart_dict[int(sku_id)] = int(cart_dict['count'])
        if cart_dict['selected']:
            new_add_selected.append(sku_id)
        else:
            new_remove_selected.append(sku_id)

    # 将数据容器中的购物车数据同步到redis数据库(重要)
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()
    # 添加到redis里
    pl.hmset('carts_%s' % user.id, new_cart_dict)
    if new_add_selected:
        pl.sadd('selected_%s' % request.user.id, *new_add_selected)
    if new_remove_selected:
        pl.srem('selected_%s' % request.user.id, *new_remove_selected)
    pl.execute()

    # 清空cookie中购物车数据
    response.delete_cookie('carts')

    return response
